import React, { Component, createRef } from "react";
import { Card, Button, Table, Modal, message } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import LinkButton from "../../components/link-button";
import { PAGE_SIZE } from "../../utils/constants";
import { formateDate } from "../../utils/dateUtils";
import { reqUsers, reqDeleteUser, reqAddOrUpdateUser } from "../../api";
import UserForm from "./user-form";
class user extends Component {
  userRef = React.createRef();
  state = {
    users: [],
    roles: [],
    isShow: false,
    // user: {},
  };
  initColums = () => {
    this.columns = [
      {
        title: "用户名",
        dataIndex: "username",
      },
      {
        title: "邮箱",
        dataIndex: "email",
      },
      {
        title: "电话",
        dataIndex: "phone",
      },
      {
        title: "注册时间",
        dataIndex: "create_time",
        render: formateDate,
      },
      {
        title: "所属角色",
        dataIndex: "role_id",
        render: (roles_id) => this.roleNames[roles_id],
      },
      {
        title: "操作",
        render: (user) => (
          <span>
            <LinkButton onClick={() => this.showUpdate(user)}>修改</LinkButton>
            <LinkButton onClick={() => this.deleteUser(user)}>删除</LinkButton>
          </span>
        ),
      },
    ];
  };
  componentWillMount() {
    this.initColums();
  }
  componentDidMount() {
    this.getUsers();
  }
  addOrUpdateUser = async () => {
    // console.log(this.userRef.current.formRef.current.getFieldsValue());
    const user = this.userRef.current.formRef.current.getFieldsValue();
    this.userRef.current.formRef.current.resetFields();
    if (this.user) {
      user._id = this.user._id;
    }

    const res = await reqAddOrUpdateUser(user);
    if (res.data.status === 0) {
      message.success(`${this.user ? "修改" : "添加"}用户成功`);
      this.getUsers();
      this.setState({ isShow: false });
    } else {
      message.error("添加用户失败");
    }
    console.log(res);
  };
  getUsers = async () => {
    const res = await reqUsers();
    console.log(res);
    if (res.data.status === 0) {
      const { users, roles } = res.data.data;

      this.initRoleNames(roles);
      this.setState({ roles, users });
      console.log(this.roleNames);
    }
  };
  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name;
      return pre;
    }, {});
    // 保存
    this.roleNames = roleNames;
  };
  deleteUser = (user) => {
    Modal.confirm({
      title: `确定删除${user.username}吗？`,
      icon: <ExclamationCircleOutlined />,
      content: "Some descriptions",
      onOk: async () => {
        const res = await reqDeleteUser(user._id);
        if (res.data.status === 0) {
          message.success("删除用户成功！");
          this.getUsers();
        } else {
          message.error("删除用户失败！");
        }
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  showUpdate = (user) => {
    this.user = user;
    console.log(user);
    this.setState({
      isShow: true,
    });
  };
  showAdd = () => {
    console.log(11);
    this.user = null;
    this.setState({
      isShow: true,
    });
  };
  render() {
    const title = (
      <Button type="primary" onClick={this.showAdd}>
        创建用户
      </Button>
    );
    const { users, isShow, roles } = this.state;
    const user = this.user;
    return (
      <Card title={title}>
        <Table
          bordered
          rowKey="_id"
          pagination={{ defaultPageSize: PAGE_SIZE, showQuickJumper: true }}
          onRow={this.onRow}
          dataSource={users}
          columns={this.columns}
        ></Table>
        <Modal
          title={user ? "修改用户" : "添加用户"}
          visible={isShow}
          onOk={this.addOrUpdateUser}
				onCancel={ () => {
			  this.userRef.current.formRef.current.resetFields()
            this.setState({ isShow: false });
          }}
        >
          <UserForm key={user} roles={roles} ref={this.userRef} user={user} />
        </Modal>
      </Card>
    );
  }
}

export default user;
